<?php
namespace app\common\component\help_to_rich;

use app\common\model\HelpToRich;
use app\common\model\HelpGetRich;

class HelpToRichService {
	public function create($data) {
		$data['order_id'] = 'TO' . date('YmdHis') . rand(1000, 9999);
		$HelpToRich = new HelpToRich($data);

    	if($HelpToRich -> save()) {
    		return [
    			'code' => 0,
    			'message' => '富豪区打款创建成功!',
    			'data' => [
    				'help_to_rich' => $HelpToRich
    			]
    		];
    	}

    	return [
			'code' => -1,
			'message' => '富豪区打款创建失败!'
		];
	}

	public function confirm($help_to_rich_id) {
		$getHelpToRich = HelpToRich::get(['help_to_rich_id' => $help_to_rich_id]);
		if(!$getHelpToRich) {
			return [
				'code' => -1,
				'message' => '订单不存在'
			];
		}

		$getHelpGetRich = HelpGetRich::get(['help_get_rich_id' => $getHelpToRich -> help_get_rich_id]);
		if(!$getHelpGetRich) {
			return [
				'code' => -1,
				'message' => '订单不存在'
			];
		}

		$currentTime = time();

		\think\Db::startTrans();
		try {
			$getHelpToRich -> begin_time = $currentTime;
			$getHelpToRich -> status = 2;
			if(!$getHelpToRich -> save()) {
				throw new \Exception('确认打款失败');
			}

			$getHelpGetRich -> begin_time = $currentTime;
			$getHelpGetRich -> status = 2;
			if(!$getHelpGetRich -> save()) {
				throw new \Exception('确认打款失败');
			}

			$confirmHelpGetRich = (new \app\common\component\help_get_rich\HelpGetRichService()) -> confirm($getHelpToRich -> help_get_rich_id);
			if($confirmHelpGetRich['code'] != 0) {
				throw new \Exception($confirmHelpGetRich['message']);
			}

			\think\Db::commit();
		} catch(\Exception $e) {
			\think\Db::rollback();

			return [
				'code' => -1,
				'message' => $e -> getMessage()
			];
		}

		return [
			'code' => 0,
			'message' => '确认打款成功'
		];
	}

	public function overtime() {
		$selectHelpToRich = HelpToRich::where('status = 1 AND over_time < ' . time()) -> select();

		if(empty($selectHelpToRich)) {
			return false;
		}

		$currentTime = time();
		foreach($selectHelpToRich as $helpToRich) {
			$helpToRich -> begin_time = $currentTime;
			$helpToRich -> status = 8;

			\think\Db::startTrans();
			try {
				if(!$helpToRich -> save()) {
					throw new \Exception('超时失败修改');
				}

				if(!\app\common\component\user\UserModel::where('user_id', $helpToRich -> user_id) -> update(['status' => 4])) {
					throw new \Exception('超时失败修改');
				}

				if(!HelpGetRich::where('help_get_rich_id', $helpToRich -> help_get_rich_id) -> update([
					'help_to_rich_id' => 0,
					'begin_time' => $currentTime,
					'status' => 0,
					'sort' => 0
				])) {
					throw new \Exception('超时失败修改');
				}

				\think\Db::commit();
			} catch(\Exception $e) {
				\think\Db::rollback();

				//$e -> getMessage();
			}
		}
	}
}
?>